import axios, {
    AxiosInstance,
    AxiosRequestConfig,
    AxiosRequestHeaders,
    AxiosResponse,
    AxiosError
} from 'axios'

import {ElMessage} from 'element-plus'

import qs from 'qs'

import {config} from '@/config/axios/config'
import {useCache} from '@/hooks/web/useCache'

const {wsCache} = useCache()
// import { tansParams } from '@/utils/dict'

const {result_code, base_url} = config
export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH]

// 创建axios实例
const service: AxiosInstance = axios.create({
    baseURL: PATH_URL, // api 的 base_url
    timeout: config.request_timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        if (
            config.method === 'post' &&
            (config.headers as AxiosRequestHeaders)['Content-Type'] ===
            'application/x-www-form-urlencoded'
        ) {
            config.data = qs.stringify(config.data)
        }
        // get参数编码
        if (config.method === 'get' && config.params) {
            let url = config.url as string
            let result = '' as string
            const keys = Object.keys(config.params)
            for (const propName of keys) {
                const value = config.params[propName]
                const part = encodeURIComponent(propName) + '='
                if (value !== null && value !== '' && typeof value !== 'undefined') {
                    if (typeof value === 'object') {
                        for (const key of Object.keys(value)) {
                            if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
                                const params = propName + '[' + key + ']'
                                const subPart = encodeURIComponent(params) + '='
                                result += subPart + encodeURIComponent(value[key]) + '&'
                            }
                        }
                    } else {
                        result += part + encodeURIComponent(value) + '&'
                    }
                }
            }
            url = config.url + '?' + result
            config.params = {}
            config.url = url
        }
        return config
    },
    (error: AxiosError) => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// const JSONbigStringTmp = require('json-bigint')
// const JSONbigString = JSONbigStringTmp({ storeAsString: true })
// response 拦截器
service.interceptors.response.use(
    (response: AxiosResponse<Recordable>) => {
        if (response.data.code === result_code) {
            return response.data
        } else if (
            //二进制数据则直接返回
            response.request.responseType === 'blob' ||
            response.request.responseType === 'arraybuffer'
        ) {
            return response.data
        } else if (response.data.code === 401) {
            //登录状态过期
            ElMessage.error(response.data.msg)
            wsCache.clear()
            setTimeout(() => {
                location.href = 'https://app.changjkj.com/#/login'
            }, 1000)
        } else {
            ElMessage.error(response.data.msg)
        }
    },
    (error: AxiosError) => {
        console.log('err' + error) // for debug
        ElMessage.error(error.message)
        return Promise.reject(error)
    }
)

export {service}
